﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Office.Interop.Word;
using System.Net.Mime;
using KOPLibrary.DataManagement;

namespace KOPLibrary.MailManagement
{
    public class HtmlBodyData
    {
        public List<Attachment> Attachments { get; private set; }
        public string HtmlBody { get; private set; }
        public HtmlBodyData(List<Attachment> attchs, string htmlbody)
        {
            Attachments = attchs;
            HtmlBody = htmlbody;
            CorrectBody();
        }

        // Word Bug
        public void CorrectBody()
        {
            MatchCollection fieldMatches = Regex.Matches(HtmlBody, AbstractData.FieldRegEx);
            StringBuilder sb = new StringBuilder(HtmlBody);
            foreach (Match m in fieldMatches)
            {
                sb.Replace(m.ToString() + " #}", m.ToString().Replace("\r\n", " ") + " #}");
            }
            HtmlBody = sb.ToString();
        }
    }


    public static class MailManager
    {

        public static string HtmlTempFolder
        {
            get
            {
                string path = Path.Combine(Path.GetTempPath(), "Kalitte_KOP\\");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                return path;
            }
        }

        public static void RemoveAllTempFiles()
        {
            try
            {
                if (Directory.Exists(HtmlTempFolder)) Directory.Delete(HtmlTempFolder, true);
            }
            catch
            { ; }
        }

        public static HtmlBodyData DocToHtmlForMail(Microsoft.Office.Interop.Word.Document doc, bool quit)
        {
            string folderpath = Path.Combine(HtmlTempFolder, Guid.NewGuid().ToString());

            if (!Directory.Exists(folderpath)) Directory.CreateDirectory(folderpath);

            string filename = Path.Combine(folderpath, Guid.NewGuid().ToString() + ".htm");
            string html = null;
            doc.SaveAs(filename, FileFormat: WdSaveFormat.wdFormatFilteredHTML,
            InsertLineBreaks: true,
            LineEnding: true,
            EmbedTrueTypeFonts: true, AddToRecentFiles: false);
            doc.Application.ActiveWindow.View.Type = WdViewType.wdPrintView;
            if (quit)
            {
                doc.Close(SaveChanges: true);

                try { doc.Application.Quit(SaveChanges: true); }
                catch { };
            }
            else doc.Close();

            StreamReader sr = new StreamReader(filename, Encoding.GetEncoding(1254));
            html = sr.ReadToEnd();
            sr.Close();


            string rexp = "src=\".+/.+\\.(jpg|gif|png|tiff|bmp|jpeg|tif)\"";
            Regex rg = new Regex(rexp);
            MatchCollection coll = rg.Matches(html);
            List<Attachment> attchs = new List<Attachment>();
            for (int i = 0; i < coll.Count; i++)
            {
                Attachment at = new Attachment(Path.Combine(folderpath, coll[i].Value.Replace("src=\"", string.Empty).Trim('"').Replace('/', '\\')));
                at.ContentId = "image" + i.ToString();
                attchs.Add(at);
                html = html.Replace(coll[i].Value, "src=\"cid:image" + i.ToString() + "\"");
            }

            //if (Directory.Exists(folderpath)) Directory.Delete(folderpath,true);

            return new HtmlBodyData(attchs, html);
        }
    }
}
